<template>
  <div>
    <el-card class="cardBox">
      <div class="monitor-grid">
        <div v-for="index in 16" :key="index" class="camera-item">
          <div class="camera-container">
            <!-- 网络摄像头画面展示 -->
            <video
              class="camera-video"
              :ref="(el) => setVideoRef(el, index)"
              autoplay
              playsinline
              muted
              @loadeddata="onVideoLoaded(index)"
              @error="onVideoError(index)"
            ></video>

            <!-- 状态提示 -->
            <div v-if="loadingStates[index]" class="status">正在连接...</div>
            <div v-if="errorStates[index]" class="error">连接失败</div>

            <!-- 摄像头编号 -->
            <div class="camera-number">摄像头 {{ index }}</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 公司log -->
    <el-row>
      <div class="kx-log-box">
        <img
          class="kx-img"
          src="@/assets/images/kxauto.png"
          alt="描述图片的文字"
        />
        <span>开轩自动化</span>

        <span class="kx-hezuo">
          商务合作：18509234888（同微信） 技术支持：18691805301（同微信）
        </span>
      </div>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

// 响应式数据
const videoRefs = ref<{ [key: number]: HTMLVideoElement | null }>({});
const loadingStates = ref<{ [key: number]: boolean }>({});
const errorStates = ref<{ [key: number]: boolean }>({});

// 设置视频引用
const setVideoRef = (el: any, index: number) => {
  videoRefs.value[index] = el;
};

// 16个不同的测试视频地址
const getCameraUrl = (index: number) => {
  const videoUrls = [
    "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4",
    "https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.m3u8",
    "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4",
    "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4",
    "https://storage.googleapis.com/webm-bucket-test/output_480p.webm",
    "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4",
    "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4",
    "https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.m3u8",
    "https://cph-p2p-msl.akamaized.net/hls/live/2000341/test/master.m3u8",
    "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
    "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
    "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4",
    "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4",
    "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
    "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_2mb.mp4",
    "https://sample-videos.com/zip/10/mp4/SampleVideo_1920x1080_1mb.mp4",
  ];

  // 循环使用视频地址，确保16个摄像头都有不同的地址
  return videoUrls[(index - 1) % videoUrls.length];
};

// 连接摄像头
const connectCamera = async (index: number) => {
  const videoRef = videoRefs.value[index];
  if (!videoRef) return;

  loadingStates.value[index] = true;
  errorStates.value[index] = false;

  try {
    const url = getCameraUrl(index);
    console.log(`连接摄像头 ${index}: ${url}`);
    videoRef.src = url;
    await videoRef.load();
  } catch (err) {
    errorStates.value[index] = true;
    console.error(`摄像头 ${index} 连接错误:`, err);
    loadingStates.value[index] = false;
  }
};

// 视频加载成功
const onVideoLoaded = (index: number) => {
  loadingStates.value[index] = false;
  errorStates.value[index] = false;
  console.log(`摄像头 ${index} 连接成功`);
};

// 视频加载错误
const onVideoError = (index: number) => {
  loadingStates.value[index] = false;
  errorStates.value[index] = true;
  console.error(`摄像头 ${index} 加载错误`);
};

// 连接所有摄像头
const connectAllCameras = () => {
  for (let i = 1; i <= 16; i++) {
    // 初始化状态
    loadingStates.value[i] = false;
    errorStates.value[i] = false;

    // 延迟连接，避免同时发起太多请求
    setTimeout(() => {
      connectCamera(i);
    }, i * 200);
  }
};

// 组件挂载时自动连接所有摄像头
onMounted(() => {
  connectAllCameras();
});

// 组件卸载时清理
onUnmounted(() => {
  Object.values(videoRefs.value).forEach((videoRef) => {
    if (videoRef) {
      videoRef.src = "";
      videoRef.load();
    }
  });
});
</script>

<style lang="scss" scoped>
.el-card__body {
  padding: 0 !important;
}

.cardBox {
  background-color: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
  border: 1px solid var(--el-border-color-light);
  flex: 1;
  display: flex;
  margin-bottom: 20px;
  min-height: 0; // 重要：防止flex项溢出

  // 确保 cardBox 内部布局正确
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex: 1;
    min-height: 0;
  }
}

.monitor-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(4, 1fr);
  gap: 5px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  min-height: 0; // 重要：防止网格溢出
}

.camera-item {
  position: relative;
  // min-height: 0; // 重要：防止网格项溢出
  // 移除固定宽高比，使用自适应
  height: 300px;
}

.camera-container {
  position: relative;
  width: 100%;
  height: 100%;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  background-color: #000;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 0;
}

.camera-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  min-height: 0;
}

.status,
.error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 12px;
  text-align: center;
  z-index: 2;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 6px 10px;
  border-radius: 4px;
  white-space: nowrap;
}

.status {
  color: #67c23a;
}

.error {
  color: #f56c6c;
}

.camera-number {
  position: absolute;
  top: 5px;
  left: 5px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px;
  border-radius: 4px;
  font-size: 16px;
  z-index: 2;
}

// 响应式适配
@media (max-width: 1600px) {
  .monitor-grid {
    gap: 12px;
    padding: 16px;
  }
}

@media (max-width: 1200px) {
  .monitor-grid {
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(6, 1fr);
  }
}

@media (max-width: 992px) {
  .monitor-grid {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(8, 1fr);
    gap: 10px;
    padding: 12px;
  }
}

@media (max-width: 768px) {
  .monitor-grid {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(16, 1fr);
    gap: 8px;
    padding: 10px;
  }

  .app-container {
    padding: 10px;
    height: calc(100vh - 64px);
  }
}

// 超小屏幕适配
@media (max-width: 480px) {
  .monitor-grid {
    gap: 6px;
    padding: 8px;
  }

  .camera-number {
    font-size: 10px;
    padding: 1px 4px;
  }

  .status,
  .error {
    font-size: 11px;
    padding: 4px 8px;
  }
}
</style>